package com.solarStruggle.controls

import java.awt.{Color, Graphics, Point}
import scala.swing.Panel
import scala.swing.event.{MouseClicked, MouseMoved}
import util.Random
import domain.{Galaxy, SolarSystem}

class GalaxyMap(state: GuiState)
extends Panel {
  
  var highlightedSolarSystem: Option[SolarSystem] = None
  
  def getCurrentSolarSystem(p: Point): Option[SolarSystem] =
    if(!state.currentGame.isEmpty && p.x >= 0 && p.y >= 0 && p.x < Galaxy.Size && p.y < Galaxy.Size) {
      Some(state.currentGame.get.galaxy.solarSystems(state.currentGame.get.galaxy.solarSystemRegions(p.x)(p.y)))
    } else {
      None
    }
  
  state.reactions += { case CurrentGameChanged(game) => peer.repaint() }
  
  Mouse.clicks.reactions += { case MouseClicked(_, p, _, _, _) =>
    state.currentSolarSystem = getCurrentSolarSystem(p)
  }
    
  Mouse.moves.reactions += { case MouseMoved(_, p, _) =>
    getCurrentSolarSystem(p) match {
      case Some(ss) =>
        highlightedSolarSystem = Some(ss)
        peer.repaint(0, 0, Galaxy.Size, Galaxy.Size)
      case None =>
    }
  }
  override def paintComponent(g: Graphics) {
    state.currentGame match {
      case Some(game) => 
        g.setColor(new Color(0, 10, 40))
        g.fillRect(0, 0, Galaxy.Size, Galaxy.Size)

        val r = new Random()
        game.galaxy.wormholes.foreach { c =>
          val color = (r.nextRangedFloat(0.8f, 1.0f) * 128).toInt
          g.setColor(new Color(color, color, color))
          val s1 = game.galaxy.solarSystems(c.solarSystem1Index)
          val s2 = game.galaxy.solarSystems(c.solarSystem2Index)
          g.drawLine(s1.x, s1.y, s2.x, s2.y)
        }

        game.galaxy.solarSystems.foreach { s =>
          g.setColor(new Color(0, 0, 0))
          g.fillOval(s.x - 5, s.y - 5, 10, 10)
          
          if(!highlightedSolarSystem.isEmpty && s == highlightedSolarSystem.get) {
            val name = highlightedSolarSystem.get.name
            val nameHeight =  g.getFontMetrics.getHeight
            val nameWidth = g.getFontMetrics.stringWidth(name)
            
            g.fillRect(s.x + 5, s.y - 5 - nameHeight, nameWidth + 8, nameHeight + 4)
            g.setColor(new Color(170, 150, 60))
            g.fillRect(s.x + 7, s.y - 3 - nameHeight, nameWidth + 6, nameHeight + 2)
            g.setColor(new Color(0, 0, 0))
            g.drawString(name, s.x + 9, s.y - (nameHeight / 2))
            g.setColor(new Color(255, 255, 255))
          } else {
            g.setColor(new Color(160, 137, 44))
          }
          g.fillOval(s.x - 3, s.y - 3, 6, 6)
        }
      case None =>
    }
  }
}
